#include <boost/format.hpp>
#include <Windows.h>
#include "timer/ProfilerManager.h"

namespace timer
{

	ProfilerManager & ProfilerManager::getInstance()
	{
		static ProfilerManager manager;
		return manager;
	}

	void ProfilerManager::Clear()
	{
		ProfilerMapIterator it = m_profiler_map.begin();
		ProfilerMapIterator end = m_profiler_map.end();
		for (;it != end; it++)
		{
			delete it->second;
		}
		m_profiler_map.clear();
	}

	ProfilerManager::ProfilerManager( void )
	{

	}

	ProfilerManager::~ProfilerManager( void )
	{
		DebugPrintInfo();
		Clear();
	}

	void ProfilerManager::getPrioritySet( SortedProfilerSet &_SortedSet ) const
	{
		ProfilerMapConstIterator it = m_profiler_map.begin();
		ProfilerMapConstIterator end = m_profiler_map.end();
		for (;it != end; it++)
		{
			_SortedSet.insert(it->second);
		}
	}

	void ProfilerManager::DebugPrintInfo() const
	{
		SortedProfilerSet sorted_set;
		getPrioritySet(sorted_set);

		SortedProfilerSetConstIterator it = sorted_set.begin();
		SortedProfilerSetConstIterator end = sorted_set.end();
		for (;it != end; it++)
		{
			ProfilerInfo const *info = *it;
			boost::format formater(std::string("[Profiling] %1% [%2%]\n") +
				"[Profiling] %3%\n" + 
				"[Profiling] \tAverage Invocation Time          : \t%4%\n" + 
				"[Profiling] \tAverage Frequent Invocation Time : \t%5%\n" + 
				"[Profiling] \tNumber of Invocation Times       : \t%6%\n" + 
				"[Profiling] \n");
			formater %info->FileName %info->LineNumber %info->FunctionSignature %info->AvgInvocationTime %info->AvgFrequentInvocationTime %info->InvocationTimes;
			std::string output = formater.str();
 			OutputDebugString(TEXT(output.c_str()));
		}
	}

}